local l_mingcha = fk.CreateSkill {
  name = "l_mingcha",
  lord_skill = true,
  frequency = Skill.Compulsory,
}

Fk:loadTranslationTable {
  ["l_mingcha"] = "明察",
  [":l_mingcha"] = "游戏开始时，你选择一名角色并查看其身份。若为反贼，则展示其身份，否则不展示。无论结果如何，均向所有玩家广播结果。",
  ["#MingchaSelect"] = "明察：选择一名角色查看其身份",
  ["#MingchaReveal"] = "%from 使用〖明察〗查看 %to 的身份",
  ["#MingchaResult"] = "%from 发现 %to 是反贼！",
  ["#MingchaNotRebel"] = "%from 发现 %to 并非反贼",
}

l_mingcha:addEffect(fk.GameStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    -- 获取除自己外的所有存活玩家
    local targets = table.filter(room.alive_players, function(p)
        return p ~= player
    end)
    
    if #targets == 0 then 
        return false 
    end
    
    -- 使用可靠的玩家选择方法
    local chosen = room:askToChoosePlayers(player, {
        min_num = 1,
        max_num = 1,
        targets = targets,
        skill_name = self.name,
        prompt = "#MingchaSelect",
        cancelable = true,
    })
    
    if chosen and #chosen > 0 then
        -- 直接使用选择的玩家对象
        event:setCostData(self, {target = chosen[1]})
        return true
    end
    return false
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targetPlayer = event:getCostData(self).target
    local isRebel = targetPlayer.role == "rebel"
    
    -- 向所有玩家广播查看结果
    room:sendLog {
      type = "#MingchaReveal",
      from = player.id,
      to = { targetPlayer.id },
      arg = targetPlayer.role,
    }
    
    -- 如果是反贼则展示身份
    if isRebel then
      room:sendLog {
        type = "#MingchaResult",
        from = player.id,
        to = { targetPlayer.id },
      }
      room:setPlayerProperty(targetPlayer, "role_shown", true)
    else
      room:sendLog {
        type = "#MingchaNotRebel",
        from = player.id,
        to = { targetPlayer.id },
      }
    end
  end
})

return l_mingcha